import { createRouter, createWebHistory } from 'vue-router'
import routes from './component/routes'
import convertRoute from './component/convertRoute'
import { getToken, getMenus, setMenus } from 'src/util/auth'
import { listMenu } from 'src/api/home'
import GlobalStore from 'src/store/global'

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from) => {
  if (to.name === 'login') return true

  const token = getToken()
  if (!token && to.name !== 'login') {
    return '/login'
  }

  const globalStore = GlobalStore()

  // 判断是否刷新
  if (!globalStore.activeMenu) {
    globalStore.changeActiveMenu(to.path)
  }

  // 判断是否异步加载路由
  const flag = globalStore.routerAdd
  if (flag) {
    return true
  }

  // 异步加载路由
  globalStore.changeRouterAdd(true)
  const menus = getMenus()
  if (menus && menus.length > 0) {
    convertRoute(router, menus)
    return to.path
  }
  listMenu().then(({ data }) => {
    setMenus(data)
    convertRoute(router, data)
    return to.path
  })
})

export default router
